package br.com.wssa.smmb.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.wssa.smmb.dao.GenericDAO;

/**
 * Classe GenericDAOImpl.
 * @author ssilva
 * @param <T>
 */
@Transactional(propagation=Propagation.SUPPORTS)
public abstract class GenericDAOImpl<T> implements GenericDAO<T> {
	@Autowired
	private SessionFactory sessionFactory;
	
	/**
	 * @return
	 */
	protected Session getSession() {
		return getSessionFactory().getCurrentSession();
	}
	
	/**
	 * @return
	 */
	protected abstract Class<?> getClazz();
	
	
	public void persistir(T objeto) {
		getSession().saveOrUpdate(objeto);
	}
	
	public void excluir(T objeto) {
		getSession().delete(objeto);
	}
	
	@SuppressWarnings("unchecked")
	public T get(Long id) {
		return (T) getSession().get(getClazz(), id);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> list(int offset, int max) {
		return (List<T>) getSession().createCriteria(getClazz()).setMaxResults(max).setFirstResult(offset).list();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
